<?php
namespace Admin\Controller;
use Think\Verify;
use Think\Controller;

class IndexController extends Controller 
{
    public function __construct()  
    {  
        parent::__construct();  
        $res = isLogin();

        if($res == '1')
        {
			$this->redirect('/Admin/Login/index');
            //$this -> error('还未登录',__APP__.'/Admin/Login/index');
        }
    }

	/*登录首页*/
    public function index()
    {
    	$arr['user_Id'] = session('user_id');
    	$UserModer = D('User');
		$res       = $UserModer->where($arr)->select();

        //获取可返积分单元
        $weightModer = D('Weight');
        $weightRes   = $weightModer->num($arr['user_Id']);
        $num = count($weightRes);

    	//获取日志条数
		$LogModer = D('Log');
		$logRes = $LogModer->index($arr['user_Id']);
		$length = count($logRes);

        //获取提现记录
        $payModer = D('Pay');
        $payRes   = $payModer->num($arr['user_Id']);
        $payRes1   = $payModer->numOne($arr['user_Id']);
        $payRes2   = $payModer->numTwo($arr['user_Id']);
        $payNum = count($payRes)+count($payRes1)+count($payRes2);
		//获取权重
        $configModer = M('config');
        $configRes   = $configModer->select();
        $weight = $configRes[0]['weight'];

		$this->assign('weight', $weight);
		$this->assign('length', $length);
    	$this->assign('user', $res);
        $this->assign('num', $num);
        $this->assign('payNum', $payNum);
        $this->display();
    }
    /*退出*/
    public function seigOut()
    {
    	session('user_id', 0);
    	session('openid', 0);
		session_destroy();
        $this->success('已退出登录！', __APP__.'/Admin/Login/index');
    }

    /*可返单元*/
    public function weight()
    {
        $arr['user_Id'] = session('user_id');
        //获取可返积分单元
        $weightModer = D('Weight');
        $weightRes       = $weightModer->num($arr['user_Id']);
        //获取用户信息
        $UserModer = D('User');
        $res       = $UserModer->where($arr)->select();

        $this->assign('weightRes', $weightRes);
        $this->assign('res', $res);
        $this->display();
    }

    /*提现记录*/
    public function pay()
    {
        $arr['user_Id'] = session('user_id');
        //获取审核不通过的记录
        $payModer = D('Pay');
        $payRes1   = $payModer->numTwo($arr['user_Id']);
        //获取未审核的记录
        $payRes2  = $payModer->numOne($arr['user_Id']);
        //获取已提现记录
        $payRes   = $payModer->num($arr['user_Id']);
        
        $this->assign('payRes1', $payRes1);
        $this->assign('payRes2', $payRes2);
        $this->assign('payRes', $payRes);
        $this->display();
    }

    /*推荐记录*/
    public function tuijian()
    {
        $arr['user_Id'] = session('user_id');
        $arr['reason'] = '赠送积分';
        $arr['is_tj'] = 1;

        $UserModer = M('Log');
        $res       = $UserModer->where($arr)->select();
        $this->assign('res', $res);
        $this->display();
    }

    /*验证码*/
    public function miti()
    {
    	$Verify = new \Think\Verify();
		$Verify->fontSize = 30;
		$Verify->length   = 4;
		$Verify->useNoise = false;
		$Verify->entry();
    }

    /*密码修改*/
    public function reset($pwd = ' ')
    {
        $this->display();
    }

     /*确认密码修改*/
    public function resetIn()
    {
        $arr['user_Id'] = session('user_id');
        $arr['oldPwd'] = md5(I('post.oldPwd'));
        $arr['newPwd1'] = md5(I('post.newPwd1'));
        $arr['newPwd2'] = md5(I('post.newPwd2'));
        $arr['check'] = I('post.check');

        $userModel = D('User');
        $userRes = $userModel->pwd($arr);

        if($userRes == 'onEq') 
        {
            $this -> error('验证码不正确！');
        }elseif($userRes == 'error')
        {
            $this->error('两次新密码不一样！');
        }elseif($userRes == 'oldErr')
        {
            $this -> error('旧密码填写错误！');
        }elseif($userRes == 'err')
        {
            $this -> error('密码修改失败！',  __APP__.'/Admin/Index/index');
        }elseif($userRes == 'success')
        {
            $this -> success('密码修改成功！',  __APP__.'/Admin/Index/index');
        }

        
    }

    /*积分日志*/
    public function pay_points()
    {
    	$arr['user_Id'] = session('user_id');

    	$UserModer = M('Log');
		$res       = $UserModer->where($arr)->order('shijian desc')->select();

		$this->assign('pointsRes', $res);
		$this->display();
    }

    /*我是商家*/
/*     public function shop()
    {
        $arr['user_Id'] = session('user_id');

        $UserModer = D('User');
        $res_shop  = $UserModer->shop($arr['user_Id']);

        $this->assign('shop', $res_shop);
        $this->display();
    } */
    public function shop()
    {
        $arr['user_Id'] = session('user_id');

        $UserModer = D('User');
        
        $res_shop  = $UserModer->myfans($arr['user_Id'], 'shop');
        //var_dump($res);exit;

       
        $this->assign('shopfans', $res_shop);
        $this->display();
    }
	
	
	
    /*我的粉丝*/
    public function fans()
    {
        $arr['user_Id'] = session('user_id');

        $UserModer = D('User');
        $res_user  = $UserModer->myfans($arr['user_Id'], 'user');
        $res_shop  = $UserModer->myfans($arr['user_Id'], 'shop');
        //var_dump($res);exit;

        $this->assign('userfans', $res_user);
        $this->assign('shopfans', $res_shop);
        $this->display();
    }

    /*消费积分*/
    public function xiaofei()
    {
        $arr['user_Id'] = session('user_id');
        $arr['reason'] = '消费积分';

        $UserModer = M('Log');
        $res       = $UserModer->where($arr)->order("shijian desc")->select();

        $this->assign('res', $res);
        $this->display();
    }

    /*赠送积分*/
    public function zengsong()
    {
        $arr['user_Id'] = session('user_id');
        $arr['reason'] = '赠送积分';
        $UserModer = M('Log');
        $res       = $UserModer->where($arr)->order('shijian desc')->select();
		
		$weight['user_id'] = session('user_id');
		$weightModer = M('weight');
        $wres       = $weightModer->where($weight)->order('shijian desc')->select();

		$this->assign('wres', $wres);
        $this->assign('res', $res);
        $this->display();
    }
	
	/*提现*/
	
	/*我要提现*/
    public function tixian()
    {
    	$arr['user_Id'] = session('user_id');
    	$UserModer = D('User');
		$res       = $UserModer->where($arr)->select();
		$this->assign('user', $res);		
        $this->display();
    }
    /*发起提现申请*/
    public function cash()
    {
		$pay['user_id'] = session('user_id');
        $user['phone']   = trim(I('post.phone'));
        $pay['number']   = trim(I('post.number'));

		if($pay['number'] < 0){
			$this->error('提现金额不能小于0',  __APP__.'/Admin/Index/index');
			exit();			
		}
		
        $userModel = M('user');
        $useRes = $userModel->where($user)->find();
		
		if(empty($useRes['name']) || empty($useRes['idcard']) || empty($useRes['openbank']) || empty($useRes['card']) ){
			$this->error('请先完善个人提现银行卡信息',  __APP__.'/Admin/Index/bankCard');
			exit();			
		}

		if((float)$useRes['use_points'] < (float)$pay['number']){
			$this->error('提现金额不能大于可提现积分',  __APP__.'/Admin/Index/index');
			exit();
		}		
		
		//print_r($useRes['user_id']);
        if($pay['user_id'] == $useRes['user_id']){
            $payModer = D('Pay');
            $res       = $payModer->cash($pay);

            if($res == 'in')
            {
                $this->success('已成功发起申请！', __APP__.'/Admin/Index/index');
            }elseif ($res == 'no') 
            {
                $this->error('发起申请失败！',  __APP__.'/Admin/Index/index');
            }elseif ($res == 'noNum') 
            {
                $this->error('返还积分达到100是才可提现或者你的可提现余额不足！',  __APP__.'/Admin/Index/index');
            }
        }else{
			$this->error('提现帐号核实失败!',  __APP__.'/Admin/Index/index');
		}
		
        /*$pay['user_id'] = session('user_id');
        $pay['number']   = trim(I('post.number'));

        $payModer = D('Pay');
        $res       = $payModer->cash($pay);

        if($res == 'in')
        {
            $this->success('已成功发起申请！', __APP__.'/Admin/Index/index');
        }elseif ($res == 'no') 
        {
            $this->error('发起申请失败！',  __APP__.'/Admin/Index/index');
        }elseif ($res == 'noNum') 
        {
            $this->error('返还积分达到100是才可提现！',  __APP__.'/Admin/Index/index');
        }*/
    }
	/*提现end*/
	
	

    /*我要提现
    public function tixian()
    {
        $this->display();
    }*/
    /*发起提现申请
    public function cash()
    {
        $pay['user_id'] = session('user_id');
        $pay['number']   = trim(I('post.number'));

        $payModer = D('Pay');
        $res       = $payModer->cash($pay);
		var_dump($res);die;
        if($res == 'in')
        {	
			//获取订单信息，根据订单进行发红包
			$re = sendredpack();
			$re_status = json_decode(json_encode(simplexml_load_string($re, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
			if($re_status['return_code'] == "SUCCESS"){
				//红包发送成功
			}else{
				//红包发送失败
			}
            $this->success('已成功发起申请！', __APP__.'/Admin/Index/index');
        }elseif ($res == 'no') 
        {
            $this->error('发起申请失败！',  __APP__.'/Admin/Index/index');
        }elseif ($res == 'noNum') 
        {
            $this->error('返还积分达到100是才可提现！',  __APP__.'/Admin/Index/index');
        }
    }*/

    //管理银行卡
    public function bankCard()
    {
        $arr['user_Id'] = session('user_id');
        $UserModer = D('User');
        $res       = $UserModer->where($arr)->select();

        $this->assign('res', $res);
        $this->display();
    }

     /*确认密码修改*/
    public function bankCardIn()
    {
        $arr['user_Id'] = session('user_id');
        $arr['banktype'] = trim(I('post.bankPlace'));
        $arr['card'] = trim(I('post.card'));
        $arr['name'] = trim(I('post.name'));
        $arr['idcard'] = trim(I('post.idcard'));
        $arr['openbank'] = trim(I('post.openbank'));

        $userModel = D('User');
        $userRes = $userModel->bankCardIn($arr);

        if($userRes == 'success') 
        {
            $this -> success('修改成功！', __APP__.'/Admin/Index/index');
        }elseif($userRes == 'oldErr')
        {
            $this -> error('用户不存在！', __APP__.'/Admin/Index/index');
        }elseif($userRes == 'err')
        {
            $this -> error('修改失败！', __APP__.'/Admin/Index/index');
        }

        
    }

    //推荐商家二维码
    public function tjshop(){
        $n_url = 'http://'.$_SERVER['HTTP_HOST'].'/index.php/Seller/Login/register2/uid/'.session('user_id');
		//var_dump(session('user_id'));exit;
        $url = "http://qr.liantu.com/api.php?text=".$n_url;
        $this -> assign('url',$url);
        $this -> display();
    }
	
	//推荐会员二维码
	public function tjcode(){
		$n_url = 'http://'.$_SERVER['HTTP_HOST'].'/index.php/Admin/Login/register2/uid/'.session('user_id');
		$url = "http://qr.liantu.com/api.php?text=".$n_url;
		$this -> assign('url',$url);
		$this -> display();
	}
	
    public function watch()
    {
        $this->display();
    }	

	//现金红包
    public function sendredpack(){
		//根据传来的订单号获取发送红包的信息
		
		//获取微信账户信息
		$url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";

		$mch_billno = '1451378302' . date ( "YmdHis", time () ) . rand ( 1000, 9999 );      //商户订单号
		$mch_id = '1451378302';                         //微信支付分配的商户号
		$wxappid = 'wx4c968c7e8b6c2719';        //公众账号appid
		$send_name = "承德众鑫";                          //商户名称
		$re_openid = "oW4B11hkv_w5V4Ka8sL5ZUNF3Wk4";         //用户openid
		$total_amount = "100";                              // 付款金额，单位分
		$total_num = 1;                                          //红包发放总人数
		$wishing = "恭喜发财";                             //红包祝福语
		$client_ip = $_SERVER["REMOTE_ADDR"];                //Ip地址
		$act_name = "关注有礼";                         //活动名称
		$remark = "测试";                                      //备注
		$apikey = "fa9fa0be9ddd6050b592a3d13c4fb91e";   // key 商户后台设置的  微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置
		$nonce_str =  md5(rand());                                  //随机字符串，不长于32位
		$m_arr = array (
		'mch_billno' => $mch_billno,
		'mch_id' => $mch_id,
		'wxappid' => $wxappid,
		'send_name' => $send_name,
		're_openid' => $re_openid,
		'total_amount' => $total_amount,
		'total_num' => $total_num,
		'wishing' => $wishing,
		'client_ip' => $client_ip,
		'act_name' => $act_name,
		'remark' => $remark,
		'nonce_str'=> $nonce_str
		);
		array_filter ( $m_arr ); // 清空参数为空的数组元素
		ksort ( $m_arr ); // 按照参数名ASCII码从小到大排序

		$stringA = "";
		foreach ( $m_arr as $key => $row ) {
		$stringA .= "&" . $key . '=' . $row;
		}
		$stringA = substr ( $stringA, 1 );
		// 拼接API密钥：
		$stringSignTemp = $stringA."&key=" . $apikey;
		$sign = strtoupper ( md5 ( $stringSignTemp ) );         //签名

		$textTpl = '<xml>
		<sign><![CDATA[%s]]></sign>
		<mch_billno><![CDATA[%s]]></mch_billno>
		<mch_id><![CDATA[%s]]></mch_id>
		<wxappid><![CDATA[%s]]></wxappid>
		<send_name><![CDATA[%s]]></send_name>
		<re_openid><![CDATA[%s]]></re_openid>
		<total_amount><![CDATA[%s]]></total_amount>
		<total_num><![CDATA[%s]]></total_num>
		<wishing><![CDATA[%s]]></wishing>
		<client_ip><![CDATA[%s]]></client_ip>
		<act_name><![CDATA[%s]]></act_name>
		<remark><![CDATA[%s]]></remark>
		<nonce_str><![CDATA[%s]]></nonce_str>
		</xml>';
		$resultStr = sprintf($textTpl, $sign, $mch_billno, $mch_id, $wxappid, $send_name,$re_openid,$total_amount,$total_num,$wishing,$client_ip,$act_name,$remark,$nonce_str);
		return $this -> curl_post_ssl($url, $resultStr);
    }
	
	function curl_post_ssl($url, $vars, $second=30,$aHeader=array())
	{
		$ch = curl_init();
		//超时时间
		curl_setopt($ch,CURLOPT_TIMEOUT,$second);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
		//这里设置代理，如果有的话
		//curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
		//curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
	   
		//以下两种方式需选择一种
	   
		//第一种方法，cert 与 key 分别属于两个.pem文件
		//默认格式为PEM，可以注释
		curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
		curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/key/apiclient_cert.pem');
		// 默认格式为PEM，可以注释
		curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
		curl_setopt($ch,CURLOPT_SSLKEY,getcwd().'/key/apiclient_key.pem');
	   
		//第二种方式，两个文件合成一个.pem文件
		//curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');
	 
		if( count($aHeader) >= 1 ){
			curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
		}
	 
		curl_setopt($ch,CURLOPT_POST, 1);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
		$data = curl_exec($ch);
		if($data){
			curl_close($ch);
			return $data;
		}
		else {
			$error = curl_errno($ch);
			echo "call faild, errorCode:$error\n";
			curl_close($ch);
			return false;
		}
	}	
	
}